package com.lms.logistics_management_system.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lms.logistics_management_system.common.Constants;
import com.lms.logistics_management_system.common.Result;
import com.lms.logistics_management_system.controller.dto.UserDTO;
import com.lms.logistics_management_system.controller.dto.UserInfoDto;
import com.lms.logistics_management_system.controller.dto.WxCode2SessionRet;
import com.lms.logistics_management_system.entity.User;
import com.lms.logistics_management_system.service.UserService;
import com.lms.logistics_management_system.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.PushBuilder;
import javax.xml.crypto.Data;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired(required = false)
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private UserService userService;
    //新增和修改
    @PostMapping("/register")
    public String register(@RequestBody JSONObject req) {
        String username = req.getString("name");
        String passwd = req.getString("passwd");
        try {
            String sql = "insert into user (user_openid,user_name) value (?,?)";//,user_avatar_url,user_create_time
            jdbcTemplate.update(sql, username, passwd);
            return "success";

        } catch (Exception e) {
            System.out.println(e);
            return "failed";
        }


    }

    @PostMapping("/wx/login")
    public Result user_login(@RequestParam(value = "code") String code,@RequestParam(value = "avatarUrl")String avatarUrl,
                             @RequestParam(value = "username")String username){
        log.info("start--------------");
        String APPID = "wx9ec2093ecd8bf2cd";
        String SECRET = "52ee3e12ccaa251b6f623687b8c0e105";//填写你的APPID和SECRT
        // 1.接收小程序发送的code
        // 2.开发者服务器 登录凭证校验接口 appi + appsecret + code
        Map<String, Object> map = new HashMap<>(7);
        map.put("appid", APPID);
        map.put("secret", SECRET);
        log.info(code);
        map.put("js_code", code);//param.getCode()
        map.put("grant_type", "authorization_code");
        WxCode2SessionRet sessionRet = null;

        // 3.接收微信接口服务 获取返回的参数
        try {
            String url = "https://api.weixin.qq.com/sns/jscode2session";
            String info = HttpUtil.get(url, map);

            sessionRet = JSON.parseObject(info, WxCode2SessionRet.class);
            log.info(info);
            log.info("openid = {}, session_key = {}", sessionRet.getOpenid(),
                    sessionRet.getSession_key());

        } catch (Exception e) {
            log.error("code2session失败", e);
            return null;
        }
//        // 通过oppenid与session_key计算token
//        String token = JwtUtils.getToken( sessionRet.getOpenid(), sessionRet.getSession_key());


        String openid = sessionRet.getOpenid();
        User user = userService.getUserByOpenid( openid);


        if (user == null) {
            // 新用户信息入库
            user = new User();
            user.setOpenid(openid);
            user.setAvatarUrl(avatarUrl);
            user.setUsername(username);
            userService.save(user);
            return Result.success(sessionRet);
        }else {
            log.info("用户已存在，登录");
            user.setAvatarUrl(avatarUrl);
            user.setUsername(username);
            userService.update(user);
            System.out.println("用户已存在，登录");
            return Result.success(sessionRet);
        }
    }
}




//    UserDTO user = userService.get






//@PostMapping("/wx/login")
//public Result user_login(@RequestParam(value = "code", required = false) String code,
//                    @RequestParam(value = "rawData", required = false) String rawData,
//                    @RequestParam(value = "signature", required = false) String signature) {
//     用户非敏感信息：rawData
//     签名：signature
////    JSONObject rawDataJson = JSON.parseObject(rawData);
//    // 1.接收小程序发送的code
//    // 2.开发者服务器 登录凭证校验接口 appi + appsecret + code
//    JSONObject SessionKeyOpenId = WechatUtil.getSessionKeyOrOpenId(code);
//    // 3.接收微信接口服务 获取返回的参数
//    String openid = SessionKeyOpenId.getString("openid");
//    String sessionKey = SessionKeyOpenId.getString("session_key");
//
//    // 4.校验签名 小程序发送的签名signature与服务器端生成的签名signature2 = sha1(rawData + sessionKey)
////    String signature2 = DigestUtils.sha1Hex(rawData + sessionKey);
////    if (!signature.equals(signature2)) {
////        return Result.error(Constants.CODE_500,"签名校验失败");
////    }
//    // 5.根据返回的User实体类，判断用户是否是新用户，是的话，将用户信息存到数据库；
//
//
//    LambdaQueryWrapper<User> lqw = Wrappers.lambdaQuery();
//    lqw.eq(User::getOpenid, openid);//查找
//
//    User user = userService.getOne(lqw);
//
//
////    UserDTO user = userService.get
//    if (user == null) {
//        // 用户信息入库
//        throw new ServiceException(Constants.CODE_600,"用户名或密码错误");
////        String username = rawDataJson.getString("username");
////        String avatarUrl = rawDataJson.getString("avatarUrl");
////        user = new User();
////        user.setOpenid(openid);
////        user.setAvatarUrl(avatarUrl);
////        user.setNickname(username);
////        userService.saveUser(user);
////
////        UserDTO userDTO = new UserDTO();
////        Map<String, Object> res = new HashMap<>();
////        BeanUtils.copyProperties(user, userDTO);//将user内容copy到userdto中去
////        res.put("data", userDTO);
////        return Result.success(res);
//    }else {
//        Map<String, Object> res = new HashMap<>();
//        UserDTO userDTO = new UserDTO();
//        BeanUtils.copyProperties(user, userDTO);//将user内容copy到userdto中去
//        res.put("data", userDTO);
//
////        return Result.error(Constants.CODE_400,"参数错误");
//        return Result.success(res);
//    }
//}




//新增和修改
//    @PostMapping("/register")
//    public Result register(@RequestBody User user){
//        String username=user.getUsername();
//        String password = user.getPassword();
//        String nickname = user.getNickname();
//        String email = user.getEmail();
//        String phone=user.getPhone();
//        String isAdmin=user.getIsAdmin();
//        //校验
//        if(     StrUtil.isBlank(username)||
//                StrUtil.isBlank(password)||
//                StrUtil.isBlank(nickname)||
//                StrUtil.isBlank(email)||
//                StrUtil.isBlank(phone)||
//                StrUtil.isBlank(isAdmin)
//        ) {
//            return Result.error(Constants.CODE_400,"参数错误");
//        }
//        UserDTO userDTO=userService.register(user);
//        return Result.success(userDTO);
//    }
//
//    /*
//     * 登录接口
//     * */
//    @PostMapping("/login")
//    public Result login(@RequestParam String username,@RequestParam String password){
//        //校验
//        if(StrUtil.isBlank(username)||StrUtil.isBlank(password)){
//            return Result.error(Constants.CODE_400,"参数错误");
//        }
//        Map<String,Object>res = userService.login(username,password);
//        return Result.success(res);
//    }
//
//
//    //新增和修改
//    @PostMapping
//    public Result save(@RequestBody User user){
//        return Result.success(userService.saveUser(user));
//    }
//
//    //查询所有表格信息
//    @GetMapping
//    public List<User> findAll(){
//        return userService.list();
//    }
//
//    //删除
//    @DeleteMapping("/{id}")
//    public boolean delete(@PathVariable Integer id){
//        return userService.removeById(id);
//    }
//    //批量删除
//    @PostMapping("/del/bash")
//    public boolean deleteBash(@RequestBody List<Integer> ids){
//        return userService.removeByIds(ids);
//    }
//
//    //分页查询手写
//    //@RequestParam 将接收到的  ?pageNum=1?pageSize=10类型的进行映射
////    @GetMapping("/page")
////    public Map<String, Object> findPage(@RequestParam Integer pageNum, @RequestParam Integer pageSize,@RequestParam String username){
////        pageNum=(pageNum-1)*pageSize;
////        Integer count=userMapper.selectCount(username);
////        Map<String,Object>res=new HashMap<>();
////        List<User>data=userMapper.selectPage(pageNum,pageSize,username);
////        res.put("data",data);
////        res.put("count",count);
////        return res;
////    }
//    //mybitis-plus方式
//    @GetMapping("/page")
//    public IPage<User> findPage(@RequestParam Integer pageNum,
//                                @RequestParam Integer pageSize,
//                                @RequestParam (defaultValue = "")String search){
//        //若没有传值，则赋默认值，防止将所有数据筛选出来
//        IPage<User> page=new Page<>(pageNum,pageSize);
//        QueryWrapper queryWrapper=new QueryWrapper<User>();
////        queryWrapper.like("username",search);
////        queryWrapper.or();
//        queryWrapper.like("username",search);
//        queryWrapper.or();
//        queryWrapper.like("phone",search);
//        queryWrapper.or();
//        queryWrapper.like("campus",search);
//        queryWrapper.or();
//        queryWrapper.like("area",search);
//        queryWrapper.or();
//        queryWrapper.like("building",search);
//        queryWrapper.or();
//        queryWrapper.like("dormitory",search);
//        queryWrapper.orderByDesc("id");
//        //后台获取用户登录信息
//        User currentUser= TokenUtils.getUserInfo();
//        System.out.println("=========================当前用户信息:"+currentUser.getNickname());
//        return userService.page(page,queryWrapper);
//    }
//
//    /*
//    * 导出功能，导出当前页面中load的对象
//    * */
//    @GetMapping("/export")
//    public void export(HttpServletResponse response)throws Exception{
//        //从数据库查出数据
//        List<User>list = userService.list();
//        System.out.println(list.get(0).getAvatarUrl());
//        //创建工具类writer，写出到浏览器
//        ExcelWriter writer = ExcelUtil.getWriter(true);
//        //自定义标题名
//        writer.addHeaderAlias("username","用户名");
//        writer.addHeaderAlias("password","密码");
//        writer.addHeaderAlias("nickname","昵称");
//        writer.addHeaderAlias("email","邮箱");
//        writer.addHeaderAlias("phone","电话");
//        writer.addHeaderAlias("campus","校区");
//        writer.addHeaderAlias("area","片区");
//        writer.addHeaderAlias("building","楼幢号");
//        writer.addHeaderAlias("dormitory","宿舍号");
//        writer.addHeaderAlias("createTime","创建时间");
//        writer.addHeaderAlias("avatarUrl","头像");
//        //将list对象一次性写入到excel中，使用默认样式，强制输出标题
//        writer.write(list,true);
//        //设置浏览器响应的格式固定写法
//        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
//        Date nowtime=new Date();
//        SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
//        String nowtimstr=sdf.format(nowtime);//Date类型转换为字符串
//        String fileName = URLEncoder.encode("用户信息"+nowtimstr,"UTF-8");
//        response.setHeader("Content-Disposition","attachment;filename="+fileName+".xlsx");
//
//        //获取输出流
//        ServletOutputStream out = response.getOutputStream();
//        writer.flush(out,true);
//        out.close();
//        writer.close();
//    }
//
//    /*
//    *
//    * excel导入接口
//    * @prama
//    * @throws Exception
//    * */
//    @PostMapping("/import")
//    public boolean imp(MultipartFile file)throws Exception{
//        InputStream inputStream=file.getInputStream();
//        ExcelReader reader = ExcelUtil.getReader(inputStream);
//        List<User> list=reader.readAll(User.class);
//        //System.out.println(list);
//        return userService.saveBatch(list);
//    }
//
//
//    @GetMapping("/getUserInfo")
//    public Result getUserInfo(@RequestParam String username) {
//        return Result.success(userService.getUserInfoDtoInfo(username));
//    }
//
//    @PostMapping("/upUserInfo")
//    public Result upUserInfo(@RequestBody UserInfoDto user) {
//        return Result.success(userService.upUserInfo(user));
//    }
//    @PostMapping("/changepw")
//    public Result changepw(@RequestParam String username,
//                           @RequestParam String password,
//                           @RequestParam String newpassword){
//        return Result.success(userService.changepw(username,password,newpassword));
//    }
//    //没有任何用处，仅作为token校验
//    @PostMapping("/token")
//    public Result token(){return Result.success();}
//
//

